#include "geminai_uart.h"
void uart1_Init(void)
{
    uart_config_t uart1_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
    };
    uart_param_config(UART_NUM_1, &uart1_config);
    uart_driver_install(UART_NUM_1, 256, 0, 0, NULL, 0);
}
void RS485_Send(uint8_t *data, uint16_t len)
{
    RS485_High;
    uart_write_bytes(UART_NUM_1, (const char *)data, len);
    RS485_Low;
}
void RS485_Recv(uint8_t *data, uint16_t len)
{   
    RS485_Low;
    uart_read_bytes(UART_NUM_1, data, len,portMAX_DELAY);
}

void Meter_Init()
{
    uart_config_t meter_config = {
        .baud_rate = 4800,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
    };
    uart_param_config(UART_NUM_2, &meter_config);
    uart_driver_install(UART_NUM_2, 256, 0, 0, NULL, 0);
    uart_set_pin(UART_NUM_2, RX_Meter, RX_Meter, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);

    // xTaskCreate(Meter_Recv_task, "MeterRecvTask", 8048, NULL, 5, NULL);
}

// 在内存块中查找指定字段的函数
void* find_byte(const uint8_t* mem, size_t size, uint8_t target) {
    for (size_t i = 0; i < size; i++) {
        if (mem[i] == target) {
            return (void*)(mem + i-1);  // 找到目标字段且位置符合条件，返回指向该位置的指针
        }
    }
    return NULL;  // 没有找到符合条件的目标字段，返回 NULL
}

void Meter_Recv_task(void* tar)
{
    uint8_t *data = (uint8_t*)malloc(48); 
    uint8_t *data1;
    // sleep(15);
    while(1)
    {
        uart_read_bytes(UART_NUM_2, data, 48,portMAX_DELAY);
        data1 = find_byte(data,23,0x5a);
        if(!data1)
            continue;
        for (int i = 0; i < 24; i++) {
            printf("%02X ", (unsigned char)data1[i]);
        }
        printf("\n");
        receive_uart_handle(data1, 24);
        power_energy_print();
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

//读取1次压缩机数据
void Meter_Recv_once(void)
{
    uint8_t data[48] = {0}; 
    uint8_t *data1;
    TickType_t timeout = pdMS_TO_TICKS(3000);  // 将 3000 毫秒转换为 FreeRTOS 时钟节拍数
    int len = uart_read_bytes(UART_NUM_2, data, 48, timeout);  // 使用 3 秒的超时时间读取数据

    if (len == ESP_ERR_TIMEOUT) {
        printf("UART hlw8032 read timeout occurred!\n");
        return;
        // 在此处处理超时情况
    } else if (len < 0) {
        printf("UART hlw8032 read error occurred\n");
        // 在此处处理其他错误情况
    } else {
        // printf("Received %d bytes from UART\n", len);
        // 在此处处理接收到的数据
    }

    data1 = find_byte(data,23,0x5a);
    if(!data1){
        printf("hlw8032 recv data error\n");
        return;
    }
    receive_uart_handle(data1, 24);
    // power_energy_print();

}
